﻿using System;
using System.IO;
using System.Text;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

using Google.YouTube;
using System.Collections;

namespace CMSE.Extensions.Youtube.YouTubeVideoCT
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver : SPItemEventReceiver
    {

        private const string HEADER = "<%@ Register Tagprefix=\"SharePoint\" Namespace=\"Microsoft.SharePoint.WebControls\" Assembly=\"Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>";
        private const string NEW_HEADER = @"<%@ Assembly Name='Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' %>
                <%@ Register TagPrefix='SharePoint' Namespace='Microsoft.SharePoint.WebControls' Assembly='Microsoft.SharePoint' %>
                <%@ Import Namespace='System.IO' %>
                <%@ Import Namespace='Microsoft.SharePoint' %>
                <%@ Import Namespace='Microsoft.SharePoint.Utilities' %>
                <%@ Import Namespace='Microsoft.SharePoint.WebControls' %>";

        private const string FOOTER = "</head>";
        private const string NEW_FOOTER = @"<body>
                <form id='Form1' runat='server'>
                <SharePoint:UrlRedirector id='Redirector1' runat='server' />
                </form>
                </body>
                </html>"; 


        /// <summary>
        /// An item is being added.
        /// </summary>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            this.EventFiringEnabled = false;
            if (properties.ListItem != null)
            {
                SPFile file = properties.ListItem.File;
                if (file != null)
                {
                    byte[] byteArray = file.OpenBinary();
                    using (MemoryStream mem = new MemoryStream())
                    {
                        mem.Write(byteArray, 0, (int)byteArray.Length);

                        string content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                        content = content.Replace(HEADER, NEW_HEADER);
                        content = content.Replace(FOOTER, NEW_FOOTER);

                        file.SaveBinary(Encoding.ASCII.GetBytes(content));

                    }
                }
            }
            this.EventFiringEnabled = true;

            //base.ItemAdding(properties);
            //this.EventFiringEnabled = false;
            //if (properties != null && properties.ListItem != null)
            //{
            //    SPListItem item = properties.ListItem;
            //    SPFieldUrlValue urlValue = new SPFieldUrlValue(item[SPBuiltInFieldId.URL].ToString());

            //    Uri url = new Uri(urlValue.Url);

            //    System.Collections.Specialized.NameValueCollection nfp = System.Web.HttpUtility.ParseQueryString(url.Query);


            //    InformationExtractor info = new InformationExtractor();

            //    Video video = info.GetVideoInformation(nfp["v"]);
            //    item[SPBuiltInFieldId.AlternateThumbnailUrl] = video.Thumbnails[2].Url;
            //    //item[SPBuiltInFieldId.Duration] = video.YouTubeEntry.Duration;
            //    urlValue.Description = video.Title;
            //    item[SPBuiltInFieldId.URL] = urlValue.ToString();
            //    item[SPBuiltInFieldId.Title] = video.Title;
            //    item.SystemUpdate();

            //}
            //this.EventFiringEnabled = true;

        }

        /// <summary>
        /// An item is being deleted.
        /// </summary>
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            base.ItemDeleting(properties);
        }

        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {

            if (properties != null && properties.ListItem != null)
            {
                //this.EventFiringEnabled = false;
                //using (SPSite site = new SPSite(properties.Web.Url))
                //{
                //    using (SPWeb web = site.OpenWeb())
                //    {
                //        web.AllowUnsafeUpdates = true;
                //        SPList list = web.Lists[properties.ListId];
                //        SPListItem item = list.Items.GetItemById(properties.ListItemId);

                //        SPFieldUrlValue urlValue = new SPFieldUrlValue(item[SPBuiltInFieldId.URL].ToString());

                //        Uri url = new Uri(urlValue.Url);

                //        System.Collections.Specialized.NameValueCollection nfp = System.Web.HttpUtility.ParseQueryString(url.Query);


                //        InformationExtractor info = new InformationExtractor();

                //        Video video = info.GetVideoInformation(nfp["v"]);
                //        item[SPBuiltInFieldId.AlternateThumbnailUrl] = video.Thumbnails[2].Url;
                //        //item[SPBuiltInFieldId.Duration] = video.YouTubeEntry.Duration;
                //        urlValue.Description = video.Title;
                //        item[SPBuiltInFieldId.URL] = urlValue.ToString();
                //        item[SPBuiltInFieldId.Title] = video.Title;
                //        item.SystemUpdate(false);
                //        web.AllowUnsafeUpdates = false;
                //    }
            }
            //this.EventFiringEnabled = true;
            //}
        }


    }
}
